package com.huaqin.obeacons;

import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class MainTabActivity extends FragmentActivity {

	private FragmentTabHost mTabHost;
	private LayoutInflater layoutInflater;

	private Class fragmentArray[] = { MessageListFragment.class,
			HomeFragment.class, HistoryFragment.class, MoreFragment.class };

	private int mImageViewArray[] = { R.drawable.tab_message_btn,
			R.drawable.tab_home_btn, R.drawable.tab_history_btn,
			R.drawable.tab_more_btn };
	private String mTextviewArray[] = { "消息", "打卡", "记录", "更多" };

	private long firstBackTime;

	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_layout);
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.onAppStart();
		initView();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}

	private void initView() {
		layoutInflater = LayoutInflater.from(this);
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		int count = fragmentArray.length;

		for (int i = 0; i < count; i++) {
			TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
					.setIndicator(getTabItemView(i));
			mTabHost.addTab(tabSpec, fragmentArray[i], null);
			mTabHost.getTabWidget().getChildAt(i)
					.setBackgroundResource(R.drawable.tab_bar_background);
		}
		// 设置默认初始页
		mTabHost.setCurrentTab(1);
	}

	private View getTabItemView(int index) {
		View view = layoutInflater.inflate(R.layout.tab_item_view, null);

		ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
		imageView.setImageResource(mImageViewArray[index]);

		TextView textView = (TextView) view.findViewById(R.id.textview);
		textView.setText(mTextviewArray[index]);

		return view;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (firstBackTime + 2000 > System.currentTimeMillis()) {
			super.onBackPressed();
		} else {
			Toast.makeText(getApplicationContext(), "再按一次推出程序",
					Toast.LENGTH_SHORT).show();
		}
		firstBackTime = System.currentTimeMillis();
	}
}
